package handlers

import (
	"context"
	"log"
	"net/http"
	"strconv"

	"gitee.com/gldmmhh/kiteclient/kitex_gen/bbs"
	"gitee.com/gldmmhh/kiteclient/kitex_gen/title_service"
	"github.com/gin-gonic/gin"
)

// GetPosts 分页获取帖子列表
func GetPosts(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
	sort := c.DefaultQuery("sort", "updateTime")
	order := c.DefaultQuery("order", "desc")

	// 打印日志
	log.Printf("GetPosts: page=%d, limit=%d, sort=%s, order=%s", page, limit, sort, order)

	req := &bbs.GetPostsRequest{
		Page:  int32(page),
		Limit: int32(limit),
		Sort:  sort,
		Order: order,
	}

	resp, err := PostClient.GetPosts(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		log.Printf("error: %v", err)
		return
	}

	c.JSON(http.StatusOK, resp)
}

func GetRecommendTitle(c *gin.Context) {
	// 定义请求结构体，包含 Content 字段
	req := struct {
		Content string `json:"content"`
	}{}

	// 绑定 JSON 请求体
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Printf("GetRecommendTitle: err=%v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	log.Printf("GetRecommendTitle: content=%s", req.Content)

	// 使用 req.Content 获取 content 字符串
	titleReq := &title_service.GenerateTitleRequest{
		Content: req.Content, // 假设 title_service 结构体有 Content 字段
	}

	resp, err := TitleClient.GenerateTitle(context.Background(), titleReq)
	if err != nil {
		log.Printf("GetRecommendTitleFail: err=%v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	log.Printf("GetRecommendTitleSuccess: resp=%v", resp)

	c.JSON(http.StatusOK, resp)
}

// GetPostDetail 获取指定帖子详情
func GetPostDetail(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	// 打印日志
	log.Printf("GetPostDetail: postId=%d", postId)

	req := &bbs.GetPostDetailRequest{
		PostId: postId,
	}

	resp, err := PostClient.GetPostDetail(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	c.JSON(http.StatusOK, resp)
}

// LikePost 点赞帖子
func LikePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		LikerId int64 `json:"likerId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("LikePost: postId=%d, likerId=%d", postId, reqBody.LikerId)

	req := &bbs.LikePostRequest{
		PostId:  postId,
		LikerId: reqBody.LikerId,
	}

	resp, err := PostClient.LikePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusCreated, resp)
	} else if resp.Code == 409 {
		c.JSON(http.StatusConflict, resp)
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// CancelLikePost 取消点赞帖子
func CancelLikePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		LikerId int64 `json:"likerId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("CancelLikePost: postId=%d, likerId=%d", postId, reqBody.LikerId)

	req := &bbs.CancelLikePostRequest{
		PostId:  postId,
		LikerId: reqBody.LikerId,
	}

	resp, err := PostClient.CancelLikePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusNoContent, gin.H{})
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// SavePost 收藏帖子
func SavePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		SaverId int64 `json:"saverId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("SavePost: postId=%d, saverId=%d", postId, reqBody.SaverId)

	req := &bbs.SavePostRequest{
		PostId:  postId,
		SaverId: reqBody.SaverId,
	}

	resp, err := PostClient.SavePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusCreated, resp)
	} else if resp.Code == 409 {
		c.JSON(http.StatusConflict, resp)
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// CancelSavePost 取消收藏帖子
func CancelSavePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		SaverId int64 `json:"saverId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("CancelSavePost: postId=%d, saverId=%d", postId, reqBody.SaverId)

	req := &bbs.CancelSavePostRequest{
		PostId:  postId,
		SaverId: reqBody.SaverId,
	}

	resp, err := PostClient.CancelSavePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusNoContent, gin.H{})
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// CreatePost 发布帖子
func CreatePost(c *gin.Context) {
	var reqBody struct {
		Writer  int64  `json:"writer"`
		Summary string `json:"summary"`
		Content string `json:"content"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("CreatePost: writer=%d, summary=%s", reqBody.Writer, reqBody.Summary)

	req := &bbs.CreatePostRequest{
		Writer:  reqBody.Writer,
		Summary: reqBody.Summary,
		Content: reqBody.Content,
	}

	resp, err := PostClient.CreatePost(context.Background(), req)
	if err != nil {
		log.Printf("CreatePost failed: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusCreated, gin.H{
			"code":    resp.Code,
			"message": resp.Message,
			"postId":  resp.PostId,
		})
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// UpdatePost 修改帖子
func UpdatePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		Summary string `json:"summary,omitempty"`
		Content string `json:"content,omitempty"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("UpdatePost: postId=%d, summary=%s", postId, reqBody.Summary)

	req := &bbs.UpdatePostRequest{
		PostId:  postId,
		Summary: reqBody.Summary,
		Content: reqBody.Content,
	}

	resp, err := PostClient.UpdatePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusOK, resp)
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}

// DeletePost 删除帖子
func DeletePost(c *gin.Context) {
	postId, _ := strconv.ParseInt(c.Param("postId"), 10, 64)

	var reqBody struct {
		UserId int64 `json:"userId"`
	}
	if err := c.ShouldBindJSON(&reqBody); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"})
		return
	}

	// 打印日志
	log.Printf("DeletePost: postId=%d, userId=%d", postId, reqBody.UserId)

	req := &bbs.DeletePostRequest{
		PostId: postId,
		UserId: reqBody.UserId,
	}

	resp, err := PostClient.DeletePost(context.Background(), req)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	if resp.Code == 200 {
		c.JSON(http.StatusNoContent, gin.H{})
	} else {
		c.JSON(http.StatusBadRequest, resp)
	}
}
